package com.ltkj.common.core.utils;

/**
 * @Author gushaoliang
 * @Date 2023/9/26 9:53
 * @PackageName:com.ltkj.common.core.utils
 * @ClassName: RSAUtils
 * @Description: TODO
 * @Version 1.0
 */

import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

public class RSAUtils {

    //RSA 获取公钥的key
    public static final String RSA_PUBLIC_KEY = "RSA_PublicKey";
    //RSA 获取私钥的key
    public static final String RSA_PRIVATE_KEY = "RSA_PrivateKey";
    // 加密算法RSA
    public static final String KEY_ALGORITHM = "RSA";
    //初始化密钥大小
    public static final Integer INITIALIZE = 1024;
    //RSA最大加密明文大小
    public static final Integer MAX_ENCRYPT_BLOCK = 117;
    //RSA最大解密密文大小
    public static final Integer MAX_DECRYPT_BLOCK = 128;
    //签名算法
    public static final String SIGNATURE_ALGORITHM = "MD5withRSA";

    /**
     * 生成密钥对(公钥和私钥)
     */
    public static Map<String, Object> generateRSAKeyPair() throws NoSuchAlgorithmException {
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
        keyPairGen.initialize(INITIALIZE);
        KeyPair keyPair = keyPairGen.generateKeyPair();
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        return new HashMap<String, Object>(){{
            put(RSA_PUBLIC_KEY, publicKey);
            put(RSA_PRIVATE_KEY, privateKey);
        }};
    }

    /**
     * 获取公钥
     * @param keyMap 密钥对
     */
    public static String getRSAPublicKey(Map<String, Object> keyMap){
        Key key = (Key) keyMap.get(RSA_PUBLIC_KEY);
        return Base64Utils.encode(key.getEncoded());
    }

    /**
     * 获取私钥
     * @param keyMap 密钥对
     */
    public static String getRSAPrivateKey(Map<String, Object> keyMap){
        Key key = (Key) keyMap.get(RSA_PRIVATE_KEY);
        return Base64Utils.encode(key.getEncoded());
    }

    /**
     * 公钥加密
     * @param data 源数据
     * @param publicKey 公钥(BASE64编码)
     */
    public static byte[] encryptByPublicKey(byte[] data, String publicKey) throws Exception {
        byte[] keyBytes = Base64Utils.decode(publicKey);
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key publicK = keyFactory.generatePublic(x509KeySpec);
        // 对数据加密
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, publicK);
        int inputLen = data.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段加密
        while (inputLen - offSet > 0) {
            if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
                cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(data, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * MAX_ENCRYPT_BLOCK;
        }
        byte[] encryptedData = out.toByteArray();
        out.close();
        return encryptedData;
    }

    /**
     * 私钥解密
     * @param encryptedData 已加密数据
     * @param privateKey 私钥(BASE64编码)
     */
    public static byte[] decryptByPrivateKey(byte[] encryptedData, String privateKey) throws Exception {
        byte[] keyBytes = Base64Utils.decode(privateKey);
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.DECRYPT_MODE, privateK);
        int inputLen = encryptedData.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段解密
        while (inputLen - offSet > 0) {
            if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
                cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * MAX_DECRYPT_BLOCK;
        }
        byte[] decryptedData = out.toByteArray();
        out.close();
        return decryptedData;
    }


    /**
     * 公钥解密
     * @param encryptedData 已加密数据
     * @param publicKey 公钥(BASE64编码)
     */
    public static byte[] decryptByPublicKey(byte[] encryptedData, String publicKey) throws Exception {
        byte[] keyBytes = Base64Utils.decode(publicKey);
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key publicK = keyFactory.generatePublic(x509KeySpec);
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.DECRYPT_MODE, publicK);
        int inputLen = encryptedData.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段解密
        while (inputLen - offSet > 0) {
            if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
                cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * MAX_DECRYPT_BLOCK;
        }
        byte[] decryptedData = out.toByteArray();
        out.close();
        return decryptedData;
    }

    /**
     * 私钥加密
     * @param data 源数据
     * @param privateKey 私钥(BASE64编码)
     */
    public static byte[] encryptByPrivateKey(byte[] data, String privateKey) throws Exception {
        byte[] keyBytes = Base64Utils.decode(privateKey);
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, privateK);
        int inputLen = data.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段加密
        while (inputLen - offSet > 0) {
            if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
                cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(data, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * MAX_ENCRYPT_BLOCK;
        }
        byte[] encryptedData = out.toByteArray();
        out.close();
        return encryptedData;
    }

    /**
     * 用私钥对信息生成数字签名
     * @param data 已加密数据
     * @param privateKey 私钥(BASE64编码)
     */
    public static String sign(byte[] data, String privateKey) throws Exception {
        byte[] keyBytes = Base64Utils.decode(privateKey);
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec);
        Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
        signature.initSign(privateK);
        signature.update(data);
        return Base64Utils.encode(signature.sign());
    }

    /**
     * 校验数字签名
     * @param data 已加密数据
     * @param publicKey 公钥(BASE64编码)
     * @param sign 数字签名
     *
     */
    public static boolean verify(byte[] data, String publicKey, String sign) throws Exception {
        byte[] keyBytes = Base64Utils.decode(publicKey);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        PublicKey publicK = keyFactory.generatePublic(keySpec);
        Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
        signature.initVerify(publicK);
        signature.update(data);
        return signature.verify(Base64Utils.decode(sign));
    }


    public static void main(String[] args) throws Exception{
        System.out.println("********************生成公钥、私钥********************");
        // Map<String, Object> map = generateRSAKeyPair();
        // System.out.println("RSA公钥：" + getRSAPublicKey(map));
        // System.out.println("RSA私钥：" + getRSAPrivateKey(map));
        // String publicKey = getRSAPublicKey(map);
        // String privateKey = getRSAPrivateKey(map);
        String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCQlFvsYRf6ZSBUtZGV7Bi2hzM357gBN+ZFfZD0ZOPo/CcA13EI4Xf83bCNaTB6qk3tWKpSl0G9Ss6cAzEek7H9wTp2Qfnxj3zLMNw5+uHeyiY4bBwKKBb+WqHOcaMtyU3HsH5vpX4sK68fe0cMd1VffQ6jo2CiyEKxQzLyJid7tQIDAQAB";
        String privateKey = "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAJCUW+xhF/plIFS1kZXsGLaHMzfnuAE35kV9kPRk4+j8JwDXcQjhd/zdsI1pMHqqTe1YqlKXQb1KzpwDMR6Tsf3BOnZB+fGPfMsw3Dn64d7KJjhsHAooFv5aoc5xoy3JTcewfm+lfiwrrx97Rwx3VV99DqOjYKLIQrFDMvImJ3u1AgMBAAECgYA3gBxBg4w23PcqTYETskxSVVg+D7+9B/5nkqpAhzJOT+2RDyMfK55p/Zg20LiBfjrn7++CQPpFdiAWF8uVV1Et56Zvu9Gfzl4k70vP3EQ0v1Jsml4tqI2bGoB/k66JRlkIgaQmIiAZidU7v6rJy4BQZQocaW+C7kfWK+5+FdMjyQJBAOnVobWdLy1yTns/78KHR4Xqrq3aRP/30tBvhkdqWyxCk4XzOGc+oZZb68EMaPzYdSytCI78R+Co3GnofFJ5cacCQQCeSNAMTDJ1RgWjofTIxD6zvwdyEuFbNhGhpS9a0eVjhxLs7vsFSEaHassnJOimXUpRaf8CcWBR/XeZ47nwkPtDAkByYO4lwQpHp6ceAItN0xA4QDBLl/2yW03CaRr8qdiJENPKbMtFLUyrGLF8D473RwYh4U3TazHZgZ+3KmJNkVv3AkBJf8Yb78X+buVvdmUUVQxIqwvqDJpYoGLPjMTQh2bdMHu5Sb+GVGlruEtdgeYGWouIApBHsh3n9Kr06qoM60XBAkBVlN9RAnYCU+54uZXp5F6HC0ybCqJCeYI1lXjYKXA/9EFhMR8AA95lakmUPtQaXNIMbvgEuvf1XkoYpyp2+tx3";
        String json = "中文，abc,！@#";

        //公钥加密
        System.out.println("********************公钥加密、生成数字签名、数字签名校验、私钥解密********************");
        System.out.println("字符串：" + json);
        String encryptPublic = Base64Utils.encode(encryptByPublicKey(json.getBytes(), publicKey));
        System.out.println("公钥加密后字符串：" + encryptPublic);

        //生成数字签名
        String signKey = sign(Base64Utils.decode(encryptPublic), privateKey);
        System.out.println("公钥加密后数字签名：" + signKey);
        //校验数字签名
        boolean verify = verify(Base64Utils.decode(encryptPublic), publicKey, signKey);
        System.out.println("公钥加密后数字签名校验：" + verify);

        //私钥解密
        System.out.println("私钥解密后字符串：" + new String(decryptByPrivateKey(Base64Utils.decode(encryptPublic), privateKey)));
        //
        // System.out.println("********************私钥加密、公钥解密********************");
        // //私钥加密
        // System.out.println();
        // System.out.println("字符串：" + json);
        // String encryptPrivate = Base64Utils.encode(encryptByPrivateKey(json.getBytes(), privateKey));
        // System.out.println("私钥加密后字符串：" + encryptPrivate);
        // //公钥解密
        // System.out.println("公钥解密后字符串：" + new String(decryptByPublicKey(Base64Utils.decode(encryptPrivate), publicKey)));

    }

}
